package com.rui.study.micro.msgcenter.service.mail.impl;

import com.rui.study.commons.model.BizException;
import com.rui.study.commons.util.PrintUtil;
import com.rui.study.micro.msgcenter.model.MailWrapper;
import com.rui.study.micro.msgcenter.service.mail.MailService;
import com.rui.study.micro.msgcenter.util.StatusCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;

@Service
public class MailServiceImpl implements MailService {

    private static final Logger LOGGER = LoggerFactory.getLogger(MailServiceImpl.class);


    @Autowired
    private JavaMailSender mailSender;

    @Value("${app.mail.from}")
    private String from;

    @Override
    public void send(MailWrapper mailWrapper) {
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();

            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

            /* 发件人 */
            helper.setFrom(from);

            helper.setTo(mailWrapper.getTos());
            helper.setSubject(mailWrapper.getSubject());
            helper.setText(mailWrapper.getContent(), true);

            /* 发送... */
            mailSender.send(mimeMessage);
            LOGGER.info("Succeed to send email with subject[{}] to{}", mailWrapper.getSubject(),
                    PrintUtil.print(mailWrapper.getTos()));
        } catch (Exception e) {
            LOGGER.error("Send mail failed, caused by {}", e.getMessage());
            throw new BizException(StatusCode.MAIL_SENDING_FAILED);
        }
    }

}
